package com.feicheng.iou.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        // 设置允许Cookie
        res.addHeader("Access-Control-Allow-Credentials", "true");

        res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        // 设置允许跨域请求的方法
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        // 允许跨域请求包含content-type
        res.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");

//        res.setHeader("Set-Cookie","JSESSIONID=xxx;SameSite=None;Secure");
//        System.out.println(((HttpServletRequest) request).getMethod().toString());
//        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
//            System.out.println("进入op");
//            response.getWriter().println("ok");
//            return;
//        }
//        System.out.println("跳过");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
